<template>
  <div class="product-management">
    <!-- 搜索区域 -->
    <a-row :gutter="16" class="search-row">
      <a-col :span="8">
        <a-input
            v-model="id"
            placeholder="请输入帖子编号"
            addon-before="帖子编号" class="search-input"/>
      </a-col>
      <a-col :span="8">
        <a-input
            v-model="title"
            placeholder="请输入帖子标题"
            addon-before="帖子标题" class="search-input"/>
      </a-col>
    </a-row>

    <!-- 查询和重置按钮 -->
    <a-row :gutter="16" class="button-row">
      <a-col :span="12">
        <a-button type="primary" @click="handleSearch">查询</a-button>
        <a-button class="reset-btn" @click="handleReset">重置</a-button>
      </a-col>
    </a-row>

    <!-- Tab栏 -->
    <a-tabs :active-key="defaultActiveKey" @change="handleChange" class="tabs">
      <a-tab-pane key="all" :tab="`全部（${allCount}）`"></a-tab-pane>
      <a-tab-pane key="approved" :tab="`已审核（${approvedCount}）`"></a-tab-pane>
      <a-tab-pane key="banned" :tab="`已封禁（${bannedCount}）`"></a-tab-pane>
    </a-tabs>

    <!-- 表格区域 -->
    <a-table :data-source="filteredData" :columns="columns" rowKey="id" class="product-table"
             :scroll="{ x: 'max-content' }">

      <!-- 状态列 -->
      <template slot="status" slot-scope="text, record">
        <span v-if="record && record.banned !== undefined && record.banned !== null"
              :style="{
                color: record.banned === 1 ? '#ff4d4f' : '#52c41a',
                background: record.banned === 1 ? '#fef0f0' : '#F0F9EB',
                padding: '5px 10px'
              }">
          {{ record.banned === 1 ? '已封禁' : '已审核' }}
        </span>
      </template>

      <!-- 用户信息列 -->
      <template slot="user" slot-scope="text, record">
        <span v-if="record.users && record.users.length > 0">
          {{ record.users[0].nickname || record.users[0].username }}
        </span>
      </template>

      <!-- 操作列 -->
      <template slot="action" slot-scope="text, record" class="handle-list">
        <a-space>
          <a-button type="link" style="padding: 0px;" @click="handleDetail(record)" class="action-btn">详情</a-button>
          <a-button v-if="record.banned === 0" type="link" style="padding: 0px;" @click="handleBan(record)"
                    class="action-btn">封禁
          </a-button>
          <a-button v-if="record.banned === 1" type="link" style="padding: 0px;" @click="handleUnban(record)"
                    class="action-btn">解封
          </a-button>
          <a-button type="link" style="padding: 0px; color: red;" danger @click="handleDelete(record)"
                    class="action-btn">删除
          </a-button>
        </a-space>
      </template>
    </a-table>
    <!-- 详情模态框 -->
    <a-modal
        :visible="detailModalVisible"
        title="帖子详情"
        @ok="handleDetailCancel"
        @cancel="handleDetailCancel"
        id="a-modal"
    >
      <a-input v-model="currentRecord.id"
               addon-before="帖子编号"
               :class="['search-input','mb-16']" disabled/>
      <a-input v-model="currentRecord.title"
               addon-before="帖子标题"
               :class="['search-input','mb-16']" disabled/>
      <a-input v-model="currentRecord.content"
               addon-before="帖子内容"
               :class="['search-input','mb-16']" disabled/>
      <a-input v-if="currentRecord.users && currentRecord.users.length > 0"
               :value="currentRecord.users[0].nickname || currentRecord.users[0].username"
               addon-before="发布用户"
               :class="['search-input','mb-16']" disabled/>
      <a-input v-model="currentRecord.likes"
               addon-before="点赞数"
               :class="['search-input','mb-16']" disabled/>
      <a-input :value="currentRecord.banned === 1 ? '已封禁' : '已审核'"
               addon-before="状态"
               :class="['search-input','mb-16']" disabled/>
      <a-input v-model="currentRecord.createdAt"
               addon-before="创建时间"
               :class="['search-input','mb-16']" disabled/>

      <!-- 显示图片或视频 -->
      <!-- 显示视频 -->
      <div v-if="currentRecord.videoUrl" class="media-container">
        <video controls class="media-item" style="width: 100%; height: auto;">
          <source :src="'http://localhost:8080' + currentRecord.videoUrl" type="video/mp4" />
          您的浏览器不支持视频播放。
        </video>
      </div>

      <!-- 显示图片 -->
      <div v-else-if="currentRecord.images && currentRecord.images.length > 0" class="media-container image-gallery">
        <img
            v-for="(imageSrc, idx) in currentRecord.images"
            :key="idx"
            :src="'http://localhost:8080' + imageSrc"
            alt="Post Image"
            class="gallery-image"
        />
      </div>


    </a-modal>

    <!-- 封禁模态框 -->
    <a-modal
        :visible="banModalVisible"
        title="封禁帖子"
        @ok="handleBanConfirm"
        @cancel="handleBanCancel"
    >
      <p>确认要封禁该帖子吗？</p>
    </a-modal>

    <!-- 解封模态框 -->
    <a-modal
        :visible="unbanModalVisible"
        title="解封帖子"
        @ok="handleUnbanConfirm"
        @cancel="handleUnbanCancel"
    >
      <p>确认要解封该帖子吗？</p>
    </a-modal>

    <!-- 删除确认模态框 -->
    <a-modal
        :visible="deleteModalVisible"
        title="确认删除"
        @ok="handleDeleteConfirm"
        @cancel="handleDeleteCancel"
    >
      <p>确认要删除该帖子吗？</p>
    </a-modal>
  </div>
</template>

<script>
import { Modal} from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
import {METHOD, request} from "@/utils/request";

export default {
  components: {
    'a-modal': Modal,
  },
  data() {
    return {
      id: '',
      title: '',
      defaultActiveKey: 'all',
      allCount: 0,
      approvedCount: 0,
      bannedCount: 0,
      allData: [],
      filteredData: [],  // 用于展示的过滤后的数据
      detailModalVisible: false,  // 控制详情模态框的显示/隐藏
      banModalVisible: false,     // 控制封禁模态框的显示/隐藏
      unbanModalVisible: false,   // 控制解封模态框的显示/隐藏
      deleteModalVisible: false, // 控制删除确认模态框的显示/隐藏
      currentRecord: {},          // 当前操作的帖子记录
      columns: [
        {
          title: '帖子编号',
          dataIndex: 'id',
          key: 'id',
          width: 100,
        },
        {
          title: '帖子信息',
          dataIndex: 'title',
          key: 'title',
          scopedSlots: {customRender: 'title'},
          width: 200,
        },
        {
          title: '帖子内容',
          dataIndex: 'content',
          key: 'content',
          width: 300,
        },
        {
          title: '发布用户',
          dataIndex: 'user',
          key: 'user',
          scopedSlots: {customRender: 'user'},
          width: 100,
        },
        {
          title: '点赞数',
          dataIndex: 'likes',
          key: 'likes',
          width: 100,
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          scopedSlots: {customRender: 'status'},
          width: 100,
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          key: 'createdAt',
          width: 180,
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          scopedSlots: {customRender: 'action'},
          fixed: 'right',
          width: 150,
        }
      ],
    };
  },
  watch: {
    // 当 allData 发生变化时，重新过滤数据
    allData: 'filterData',
  },
  mounted() {
    this.filterData();  // 页面加载时初始化数据
    this.fetchData();   // 调用 fetchData 获取数据
  },
  methods: {
    // 查询按钮
    handleSearch() {
      this.filterData();
    },
    // 重置按钮
    handleReset() {
      this.id = '';
      this.title = '';
      this.defaultActiveKey = 'all'; // 重置时默认显示全部
      this.filterData(); // 重置时显示所有数据
    },
    // Tab切换
    handleChange(activeKey) {
      this.defaultActiveKey = activeKey;
      this.filterData(); // 切换Tab时重新过滤数据
    },
    // 过滤数据
    filterData() {
      let filtered = [...this.allData]; // 从 allData 复制数据以避免直接修改原始数据

      // 根据搜索条件过滤
      if (this.id) {
        filtered = filtered.filter(item => item.id.toString().includes(this.id));
      }
      if (this.title) {
        filtered = filtered.filter(item => item.title.includes(this.title));
      }

      // 根据 Tab 进行过滤
      switch (this.defaultActiveKey) {
        case 'all':
          break;
        case 'approved':
          filtered = filtered.filter(item => item.banned === 0);
          break;
        case 'banned':
          filtered = filtered.filter(item => item.banned === 1);
          break;
        default:
          break;
      }

      // 更新过滤后的数据
      this.filteredData = filtered;
      this.updateCounts();  // 更新 Tab 页统计数据
    },
    // 更新各 Tab 页的统计数
    updateCounts() {
      this.allCount = this.allData.length;
      this.approvedCount = this.allData.filter(item => item.banned === 0).length;
      this.bannedCount = this.allData.filter(item => item.banned === 1).length;
    },
    // 打开详情模态框
    handleDetail(record) {
      this.currentRecord = record;
      this.detailModalVisible = true;
    },

    // 关闭详情模态框
    handleDetailCancel() {
      this.detailModalVisible = false;
    },

    // 打开封禁模态框
    handleBan(record) {
      this.currentRecord = record;
      this.banModalVisible = true;
    },

    // 确认封禁
    handleBanConfirm() {
      this.updatePostStatus(this.currentRecord.id, 1);
      this.banModalVisible = false;
    },

    // 取消封禁
    handleBanCancel() {
      this.banModalVisible = false;
    },

    // 打开解封模态框
    handleUnban(record) {
      this.currentRecord = record;
      this.unbanModalVisible = true;
    },

    // 确认解封
    handleUnbanConfirm() {
      this.updatePostStatus(this.currentRecord.id, 0);
      this.unbanModalVisible = false;
    },

    // 取消解封
    handleUnbanCancel() {
      this.unbanModalVisible = false;
    },

    // 更新帖子状态
    async updatePostStatus(postId, status) {
      try {
        const response = await request(
            `http://localhost:8080/api/post/updateStatus`,
            METHOD.POST,
            {
              id: postId,
              banned: status
            },
            {
              headers: {
                'Accept': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem("token")
              }
            }
        );
        if (response.data.code === 200) {
          this.$message.success('操作成功');
          this.fetchData();
        } else {
          this.$message.error(response.data.msg);
        }
      } catch (error) {
        console.error(error);
        this.$message.error('操作失败');
      }
    },

    // 打开删除确认模态框
    handleDelete(record) {
      this.currentRecord = record;
      this.deleteModalVisible = true;
    },

    // 确认删除
    handleDeleteConfirm() {
      this.deletePost(this.currentRecord.id);
      this.deleteModalVisible = false;
    },

    // 取消删除
    handleDeleteCancel() {
      this.deleteModalVisible = false;
    },

    // 删除帖子
    async deletePost(postId) {
      try {
        const response = await request(
            `http://localhost:8080/api/post/delete?id=${postId}`,
            METHOD.DELETE,
            null,
            {
              headers: {
                'Accept': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem("token")
              }
            }
        );
        if (response.data.code === 200) {
          this.$message.success('删除成功');
          this.fetchData();
        } else {
          this.$message.error(response.data.msg);
        }
      } catch (error) {
        console.error(error);
        this.$message.error('删除失败');
      }
    },

    async fetchData() {
      try {
        // 调用后端 API 获取帖子信息
        const response = await request(
            `http://localhost:8080/api/post/All`,
            METHOD.GET,
            null,
            {
              headers: {
                'Accept': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem("token")
              }
            }
        );
        if (response.data.code === 200) {
          this.allData = response.data.data;
          this.filteredData = this.allData;  // 初始时过滤数据为全部数据
          this.updateCounts();
        } else {
          this.$message.error(response.data.msg);
        }
      } catch (error) {
        console.error(error);
        this.$message.error('获取数据失败');
      }
    },
  },
};
</script>

<style scoped>
.media-container {
  margin-top: 16px;
}

.gallery-image {
  max-width: 100%;
  max-height: 300px;
  margin: 8px 0;
  border-radius: 8px;
}

.product-management {
  padding: 20px;
}

.search-row {
  margin-bottom: 20px;
}

.search-input, .search-select {
  width: 100%;
}

.button-row {
  margin-top: 16px;
}

.reset-btn {
  margin-left: 8px;
}

.tabs {
  margin-top: 20px;
  background-color: whitesmoke;
  border-radius: 8px;
}

.product-table {
  background-color: whitesmoke;
  margin-top: 16px;
  max-width: 100%;
  overflow-x: auto;
}

.product-image {
  width: 50px;
  height: 50px;
}

.action-btn {
  color: #1890ff;
}

.action-btn:hover {
  color: #40a9ff;
}

.mb-16 {
  margin-bottom: 16px;
}
</style>